package com.celan.year2023.month06.day10;

import java.util.Arrays;

/**
 * @author Celan
 * @description TODO
 */
public class Solution03 {
    public int longestSubstring(String s, int k) {
        int ans = 0;
        int len = s.length();
        char[] cs = s.toCharArray();
        int[] cnt = new int[26];
        for (int curKind = 1; curKind <= 26; curKind++) {
            //对于限定的字符数量的条件下进行滑动窗口
            Arrays.fill(cnt, 0);
            int left = 0, right = 0;
            //totalKind:窗口内所有字符类型数量，sumKind:窗口内满足出现次数不少于k的字符类型数量
            int totalKind = 0, sumKind = 0;
            while (right < len) {
                int rightIndex = cs[right] - 'a';
                cnt[rightIndex]++;
                if (cnt[rightIndex] == 1) totalKind++;
                if (cnt[rightIndex] == k) sumKind++;
                //当总字符种类数量不满足限定的字符种类数量，需要被迫移动左指针来减少总字符种类数量
                while (totalKind > curKind) {
                    int leftIndex = cs[left] - 'a';
                    if (cnt[leftIndex] == 1) totalKind--;
                    if (cnt[leftIndex] == k) sumKind--;
                    cnt[leftIndex]--;
                    left++;
                }
                if (totalKind == sumKind) ans = Math.max(ans, right - left + 1);
                //主动移动右指针
                right++;
            }
        }
        return ans;
    }
}
